package com.ruge.tool.http;

import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * description: HttpResponseHandler
 * create time at 2022/11/25 16:35
 *
 * @author alice.ruge
 * @since 0.0.3
 */

public interface HttpResponseHandler<T> {

    HttpResponse<T> handler(ClassicHttpResponse response, HttpExplorer explorer);

    /**
     * 返回字符串
     *
     * @param defaultCharset 默认字符集
     */
    static HttpResponseHandler ofString(Charset... defaultCharset) {
        return (response, client) -> {
            try {
                Charset charset = defaultCharset != null && defaultCharset.length > 0 ? defaultCharset[0] : Charset.defaultCharset();
                return HttpResponse.build(response, EntityUtils.toString(response.getEntity(), charset));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
    }

    /**
     * 保存为文件
     *
     * @param path    保存文件路径
     * @param options StandardCopyOption: REPLACE_EXISTING(替换更新), COPY_ATTRIBUTES(复制属性), ATOMIC_MOVE(原子移动)
     */
    static HttpResponseHandler<File> ofFile(Path path, CopyOption... options) {
        return (response, client) -> {
            File file = path.toFile();
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            try (InputStream in = response.getEntity().getContent()) {
                Files.copy(in, path, options);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return HttpResponse.build(response, file);
        };
    }
}